import React, { memo, useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { searchContentAction } from "./store/actionCreators";

import LayoutCard from "@/components/layout-card";
import Null from "@/components/null";
import User from "@/components/user";
import { SearchWrapper, HistoryRecord, SearchFind, Result } from "./style";
import { Input, message } from "antd";
import {
  LeftOutlined,
  SearchOutlined,
  DeleteOutlined,
} from "@ant-design/icons";

// nanoid
import { nanoid } from "nanoid";

// 引入搜索推荐数据
import { searchFindData } from "@/common/local-data";

export default memo(function Search() {
  // 控制历史记录和推荐是否显示
  const [isShowHistory, setIsShowHistory] = useState(true);
  const [isShowSearchFind, setIsShowSearchFind] = useState(true);
  // 控制结果展示区域
  const [isShowResult, setIsShowResult] = useState(false);
  const [isActive, setIsActive] = useState(true);
  const [value, setValue] = useState();
  const [historyRecord, setHistoryRecord] = useState(() => {
    let data = JSON.parse(localStorage.getItem("historyRecord"));
    if (data) {
      return data;
    } else {
      return [];
    }
  });
  const history = useHistory();
  const { noteList, userList } = useSelector(
    (state) => ({
      noteList: state.getIn(["search", "noteList"]),
      userList: state.getIn(["search", "userList"]),
    }),
    shallowEqual
  );
  const dispatch = useDispatch();
  useEffect(() => {
    if (historyRecord.length < 1) {
      setIsShowHistory(false);
    }
  }, [historyRecord]);

  const jumpToHomePage = () => {
    history.goBack();
  };
  const handleValue = (e) => {
    setValue(e.target.value);
  };
  const handleSearch = () => {
    if (value) {
      // 存入localStoroge
      // 第一次进入页面
      if (historyRecord.length < 1) {
        localStorage.setItem(
          "historyRecord",
          JSON.stringify([...historyRecord, value])
        );
      } else {
        const flag = historyRecord.findIndex((item) => {
          return item === value;
        });
        if (flag < 0) {
          localStorage.setItem(
            "historyRecord",
            JSON.stringify([...historyRecord, value])
          );
        }
      }
      setIsShowHistory(false);
      setIsShowSearchFind(false);
      setIsShowResult(true);

      dispatch(searchContentAction(value));
    } else {
      message.error({
        content: "您尚未输入内容~",
        duration: 1,
        style: {
          marginTop: "40vh",
        },
      });
    }
  };
  // 清除历史记录
  const clearHistoryRecord = () => {
    localStorage.removeItem("historyRecord");
    setHistoryRecord([]);
    setIsShowHistory(false);
  };
  const handlePageOtherClick = (data) => {
    setValue(() => {
      setIsShowHistory(false);
      setIsShowSearchFind(false);
      setIsShowResult(true);
      dispatch(searchContentAction(data));
      return data;
    });
  };

  return (
    <SearchWrapper>
      <div className="head">
        <i style={{ fontSize: "18px" }} onClick={jumpToHomePage}>
          <LeftOutlined />
        </i>
        <Input
          value={value}
          onChange={handleValue}
          placeholder="请输入用户名..."
          prefix={<SearchOutlined />}
          allowClear
          style={{ width: 304 }}
        />
        <button className="btn" onClick={handleSearch}>
          搜索
        </button>
      </div>
      <div className="body">
        {isShowHistory && (
          <HistoryRecord>
            <div className="title">
              <span className="title-left">历史记录</span>
              <i onClick={clearHistoryRecord}>
                <DeleteOutlined />
              </i>
            </div>
            <div className="main">
              {historyRecord.map((item) => {
                return (
                  <div
                    className="main-item"
                    key={nanoid()}
                    onClick={(e) => {
                      handlePageOtherClick(item);
                    }}
                  >
                    {item}
                  </div>
                );
              })}
            </div>
          </HistoryRecord>
        )}
        {isShowSearchFind && (
          <SearchFind>
            <div className="title">搜索发现</div>
            <div className="main">
              {searchFindData.map((item, index) => {
                return (
                  <div className="find-item" key={nanoid()}>
                    {item}
                  </div>
                );
              })}
            </div>
          </SearchFind>
        )}
        {isShowResult && (
          <Result>
            <div className="result-title">
              <span
                className={[
                  "result-title-item ",
                  isActive ? "active" : "",
                ].join(" ")}
                onClick={(e) => setIsActive(true)}
              >
                笔记
              </span>
              <span
                className={[
                  "result-title-item ",
                  isActive ? "" : "active",
                ].join(" ")}
                onClick={(e) => setIsActive(false)}
              >
                用户
              </span>
            </div>

            <div className="result-main">
              {isActive ? (
                noteList.length !== 0 ? (
                  <LayoutCard data={noteList} />
                ) : (
                  <Null>没有找到相关笔记~</Null>
                )
              ) : userList.length !== 0 ? (
                <User data={userList} />
              ) : (
                <Null>没有找到相关用户~</Null>
              )}
            </div>
          </Result>
        )}
      </div>
    </SearchWrapper>
  );
});
